package com.taotao.sso.service.impl;

import com.taotao.mapper.UserMapper;
import com.taotao.pojo.User;
import com.taotao.sso.dao.JedisClient;
import com.taotao.sso.service.UserService;
import com.taotao.util.CookieUtils;
import com.taotao.util.JsonUtils;
import com.taotao.util.TaotaoResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author hong.zheng
 * @Description
 * @date 2018-09-25-11:07
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JedisClient jedisClient;
    /**
     *
     */
    @Value("${REDIS_USER_SESSION_KEY}")
    String REDIS_USER_SESSION_KEY;
    /**
     * session 过期
     */
    @Value("${SSO_SESSION_EXPIRE}")
    Integer SSO_SESSION_EXPIRE;



    @Override
    public TaotaoResult checkData(String content, Integer type) {
        //创建查询条件
        //对数据进行校验：1、2、3分别代表username、phone、email
        //用户名校验
        User user = new User();
        if (1 == type) {
            user.setUsername(content);
            //电话校验
        } else if ( 2 == type) {
           user.setPhone(content);
            //email校验
        } else {
            user.setEmail(content);
        }
        //执行查询
        List<User> list = userMapper.findUsers(user);
        if (list == null || list.size() == 0) {
            return TaotaoResult.ok(true);
        }
        return TaotaoResult.ok(false);
    }

    @Override
    public TaotaoResult createUser(User user) {
        //有效性验证
        if (StringUtils.isBlank(user.getUsername())) {
            return TaotaoResult.build(400, "用户名不能为空");
        }
        if (StringUtils.isBlank(user.getPassword())) {
            return TaotaoResult.build(400, "密码不能为空");
        }
        if (StringUtils.isBlank(user.getPhone())) {
            return TaotaoResult.build(400, "手机不能为空");
        }
        user.setUpdated(new Date());
        user.setCreated(new Date());
        //md5加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        userMapper.addUser(user);
        return TaotaoResult.ok();
    }

    @Override
    public TaotaoResult userLogin(String username, String password, HttpServletRequest request, HttpServletResponse response) {
        User queryUser = new User();
        queryUser.setUsername(username);
        List<User> list = userMapper.findUsers(queryUser);
        //如果没有此用户名
        if (null == list || list.size() == 0) {
            return TaotaoResult.build(400, "用户名或密码错误");
        }
        User user = list.get(0);
        //比对密码
        if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())) {
            return TaotaoResult.build(400, "用户名或密码错误");
        }
        //生成token
        String token = UUID.randomUUID().toString();
        //保存用户之前，把用户对象中的密码清空。
        user.setPassword(null);
        //把用户信息写入redis
        jedisClient.set(REDIS_USER_SESSION_KEY + ":" + token, JsonUtils.objectToJson(user));
        //设置session的过期时间
        jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE);

        CookieUtils.setCookie(request, response, "TT_TOKEN", token);
        //返回token
        return TaotaoResult.ok(token);
    }

    @Override
    public TaotaoResult getUserByToken(String token) throws Exception {
        //从redis中取用户信息
        String userJson = jedisClient.get(REDIS_USER_SESSION_KEY + ":" + token);

        if (StringUtils.isBlank(userJson)) {
            return TaotaoResult.build(400, "该用户已过期");
        }
        //把json转换成user对象
        User user = JsonUtils.jsonToPojo(userJson, User.class);
        //更新用户有效期
        jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE);

        return TaotaoResult.ok(user);
    }
}
